package com.atguigu.srb.oss.controller.api;

import com.atguigu.common.exception.MyException;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.oss.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Api(tags = "阿里云OSS文件管理")
@RestController
@RequestMapping("/api/oss")
public class ApiOssController {

    @Autowired
    private OssService ossService;

    @ApiOperation("文件上传到阿里云OSS")
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file,@RequestParam("module") String module){
        try {
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();
            String url = ossService.upload(inputStream, module, filename);
            return R.ok().data("url",url).message("文件上传成功");
        } catch (IOException e) {
           throw new MyException(ResponseEnum.UPLOAD_ERROR,e);
        }
    }

    @ApiOperation("阿里云OSS文件删除")
    @DeleteMapping("/delete")
    public R delete(@RequestParam("url") String url) {
        ossService.deleteFile(url);
        return R.ok().message("删除OSS文件成功");
    }

}
